package org.weixin4j.web;

import org.apache.log4j.Logger;
import org.weixin4j.User;
import org.weixin4j.WeixinException;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.OAuth2Token;
import org.weixin4j.http.Response;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import wechat.WXHomeController;

public class AdvancedUtil {

	static Logger logger= Logger.getLogger(WXHomeController.class);
	public static OAuth2Token getOauth2AccessToken(String appId, String appSecret, String code) throws WeixinException {
		OAuth2Token wat = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		requestUrl = requestUrl.replace("APPID", appId);
		requestUrl = requestUrl.replace("SECRET", appSecret);
		requestUrl = requestUrl.replace("CODE", code);
		// 获取网页授权凭证
		HttpsClient http = new HttpsClient();
		Response res = http.get(requestUrl);
		JSONObject jsonObject = res.asJSONObject();
		if (null != jsonObject) {
			try {
				wat = new OAuth2Token();
				wat.setAccess_token(jsonObject.getString("access_token"));
				wat.setExpires_in(jsonObject.getIntValue("expires_in"));
				wat.setRefresh_token(jsonObject.getString("refresh_token"));
				wat.setOpenid(jsonObject.getString("openid"));
				wat.setScope(jsonObject.getString("scope"));
			} catch (Exception e) {
				wat = null;
				int errorCode = jsonObject.getIntValue("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				System.out.println(Integer.valueOf(errorCode));
			}
		}
		return wat;
	}

	/**
	 * 通过网页授权获取用户信息
	 * 
	 * @param accessToken 网页授权接口调用凭证
	 * @param openId 用户标识
	 * @return SNSUserInfo
	 * @throws WeixinException 
	 */
	@SuppressWarnings( { "deprecation", "unchecked" })
	public static User getSNSUserInfo(String accessToken, String openId) throws WeixinException {
		logger.error(accessToken+"--------"+openId);
		User snsUserInfo = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
		// 通过网页授权获取用户信息
		HttpsClient http = new HttpsClient();
		Response res = http.get(requestUrl);
		JSONObject jsonObject = res.asJSONObject();
		if (null != jsonObject) {
			try {
				snsUserInfo = new User();
				// 用户的标识
				snsUserInfo.setSubscribe(jsonObject.getString("subscribe"));
				snsUserInfo.setOpenid(jsonObject.getString("openid"));
				// 昵称
				snsUserInfo.setNickname(jsonObject.getString("nickname"));
				// 性别（1是男性，2是女性，0是未知）
				snsUserInfo.setSex(jsonObject.getIntValue("sex"));
				// 用户所在国家
				snsUserInfo.setCountry(jsonObject.getString("country"));
				// 用户所在省份
				snsUserInfo.setProvince(jsonObject.getString("province"));
				// 用户所在城市
				snsUserInfo.setCity(jsonObject.getString("city"));
				// 用户头像
				snsUserInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
				snsUserInfo.setQr_scene_str(jsonObject.getString("qr_scene_str"));
				snsUserInfo.setSubscribe_time(jsonObject.getLongValue("subscribe_time"));
				// 用户特权信息
				//snsUserInfo.setPrivilegeList(JSONArray.to(jsonObject.getJSONArray("privilege"), List.class));
			} catch (Exception e) {
				snsUserInfo = null;
				int errorCode = jsonObject.getIntValue("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				logger.error(String.format("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg));
			}
		}
		return snsUserInfo;
	}
}
